<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
  <title>开始使用 layui</title>
  <meta http-equiv="Access-Control-Allow-Origin" content="*">
  <link rel="stylesheet" href="/layui/css/layui.css">
</head>
<body>
<div class="searchBar">
  名称：
  <div class="layui-inline">
    <input type="text" class="layui-input" name="name" id="name"
           autocomplete="off"/>
  </div>
  <button class="layui-btn" id="searchBtn" data-type="reload">搜索</button>
</div>
<!-- 你的 HTML 代码 -->
<table id="announcement" lay-filter="announcement"></table>
<!-- 表头信息 -->
<div id="toolbar" style="display: none;">
  <div class="layui-btn-group">
    <button class="layui-btn layui-btn-sm" lay-event="add">新增</button>
  </div>
</div>
<!--操作栏信息-->
<script type="text/html" id="operatebar">
  <a class="layui-btn layui-btn-sm" lay-event="edit">编辑</a>
  <a class="layui-btn layui-btn-sm layui-btn-danger" lay-event="delete">删除</a>
</script>
<!--新增、修改页面（模态框）
新增和修改最大的差异是：新增表单项中是没有数据的，修改的表单项中是存在数据
-->
<div id="modal" style="display: none;">
  <form class="layui-form" lay-filter="entity">
    <input type="text" name="id" style="display: none;"/>
    <div class="layui-form-item">
      <label class="layui-form-label">标题</label>
      <div class="layui-input-block">
        <input type="text" name="title" required="" lay-verify="required" placeholder="请输入标题"
               autocomplete="off" class="layui-input">
      </div>
    </div>
    <div class="layui-form-item layui-form-text">
      <label class="layui-form-label">内容</label>
      <div class="layui-input-block">
        <textarea name="contents" placeholder="请输入内容" class="layui-textarea"></textarea>
      </div>
    </div>
    <div class="layui-form-item">
      <label class="layui-form-label">状态</label>
      <div class="layui-input-block">
        <input type="radio" name="annStatus" value="0" title="正常"
               checked="">
        <div class="layui-unselect layui-form-radio"><i class="layui-anim
layui-icon"> </i>
          <div>正常</div>
        </div>
        <input type="radio" name="annStatus" value="1" title="废弃">
        <div
                class="layui-unselect layui-form-radio layui-form-radioed"><i class="layui-anim
layui-icon"> </i>
          <div>废弃</div>
        </div>
      </div>
    </div>
    <div class="layui-form-item">
      <div class="layui-input-block">
        <button class="layui-btn" lay-submit="" lay-filter="addandupdate">立即提交</button>
        <button type="reset" class="layui-btn layui-btn-primary">重置</button>
      </div>
    </div>
  </form>
</div>
<script src="/layui/layui.js"></script>
<script>
  layui.use(['table', 'layer', 'jquery', 'form'], function () {
    var table = layui.table;
    var layer = layui.layer;
    var $ = layui.jquery;
    var form = layui.form;

    table.render({
      elem: '#announcement'
      , id: 'testReload'
      , height: 472
      , url: '/api/announcement/page' //数据接口
      , page: true //开启分页
      , cols: [[ //表头
        {field: 'id', title: 'ID', sort: true, fixed: 'left'}
        , {field: 'title', title: '标题'}
        , {field: 'contents', title: '内容'}
        , {field: 'createDatetime', title: '创建时间', sort: true}
        , {
          field: 'annStatus', title: '状态', templet: function (d) {
            return d.annStatus === 0 ? "正常" : "废弃";
          }
        }
        , {field: 'annDate', title: '修改日期', sort: true}
        , {title: '操作', toolbar: '#operatebar', align: 'center'}
      ]]
      , toolbar: '#toolbar'
      , response: {
        statusCode: 1
      }
      , parseData: function (res) {
        if (res.status == 1) {
          return {
            "code": res.status,
            "msg": res.message,
            "count": res.total,
            "data": res.data
          }
        }
      }
    });
    // 监控表格的工作栏
    table.on("toolbar(announcement)", function (obj) {
      switch (obj.event) {
        case 'add':
          open2("新增公告", null);
          break;
      }
    });
    // 监控表格操作栏
    table.on("tool(announcement)", function (obj) {
      var data = obj.data;
      switch (obj.event) {
        case 'delete':
          layer.confirm("确定要删除该数据吗？", function (index) {
            // 执行删除操作
            $.ajax({
              url: '/api/announcement/' + data.id,
              type: 'delete',
              dataType: 'json',
              success: function (res) {
                if (res.status == 1) {
                  layer.msg(res.message);
                  //active.reload();
                  obj.del();
                } else {
                  layer.msg(res.message);
                }
              }
            });
            // 对话框关闭掉
            layer.close(index);
          });
          break;
        case 'edit':
          open2("修改公告", data);
          break;
      }
    });

    function open2(title, entity) {
      // 向表单中赋值
      form.val('entity', entity);
      layer.open({
        type: 1
        , title: title
        , content: $('#modal')
        , offset: '10px'
        , area: ['600px', '80%']
        , end: function () {
          //table.reload('testReload')
          active.reload();
        }
      });
    }

    // 当用户输入完信息后，点击了提交按钮，执行以下操作
    form.on("submit(addandupdate)", function () {
      // 从表单中取值
      var data = form.val("entity");
      var type = data.id ? "put" : "post";
      console.log(data);
      $.ajax({
        url: '/api/announcement',
        type: type,
        dataType: 'json',
        contentType: 'application/json',
        data: JSON.stringify(data),
        success: function (res) {
          if (res.status == 1) {
            layer.msg(res.message, {time: 1 * 1000}, function () {
              layer.closeAll();
            });
          } else {
            layer.msg(res.message);
          }
        }
      });
      return false;
    });
    var active = {
      reload: function () {
        var name = $('#name');
        // 重新加载表
        table.reload('testReload', {
          page: {
            curr: 1
          }
          , where: {
            "title": name.val()
          }
        })
      }
    };

    $('.searchBar .layui-btn').on('click', function () {
      var type = $(this).data('type');
      active[type] ? active[type].call(this) : '';
    });
  });
</script>
</body>
</html>

